package br.com.senac.pi5.servlet;

import br.com.senac.pi5.bean.Passageiro;
import br.com.senac.pi5.bean.Passagem;
import br.com.senac.pi5.dao.PassageiroDao;
import java.io.IOException;
import java.sql.SQLException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@WebServlet(name = "LogInServlet", urlPatterns = {"/LogInServlet"})
public class LogInServlet extends HttpServlet {

    @Override
    protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        response.setContentType("text/html;charset=UTF-8");

        String usuario = request.getParameter("usuario");
        String senha = request.getParameter("senha");

        try {
            PassageiroDao dao = new PassageiroDao();
            Passageiro passageiro = dao.autentica(usuario, senha);

            if (passageiro.getCodigo() == null) {
                RequestDispatcher rd = request.getRequestDispatcher("/falhaNaAutenticacao.jsp");
                rd.forward(request, response);
            } else {
                request.getSession().setAttribute("Passageiro", passageiro);
                Passagem passagem = (Passagem) request.getSession(true).getAttribute("Passagem");
                if (passagem == null) {
                    RequestDispatcher rd = request.getRequestDispatcher("/passageiroLogadoComSucesso.jsp");
                    rd.forward(request, response);
                } else {
                    RequestDispatcher rd = request.getRequestDispatcher("/detalhesPassagem.jsp");
                    rd.forward(request, response);
                }
            }
        } catch (SQLException ex) {
            Logger.getLogger(LogInServlet.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
}
